package net.wyxj.security.symmetric;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class RSA {
	public PublicKey mPublic;
	public PrivateKey mPrivate;
	private Cipher mCipher;

	public RSA() throws NoSuchAlgorithmException, NoSuchPaddingException {
		generateKey(1024);
		mCipher = Cipher.getInstance("RSA");
	}

	public RSA(int keyLength) throws NoSuchAlgorithmException,NoSuchPaddingException {
		generateKey(keyLength);
		mCipher = Cipher.getInstance("RSA");
	}

	private void generateKey(int keyLength) throws NoSuchAlgorithmException {
		if (keyLength < 500 || keyLength > 16384) {
			return;
		}
		KeyPairGenerator kpg;
		kpg = KeyPairGenerator.getInstance("RSA");
		kpg.initialize(keyLength);
		KeyPair kp = kpg.generateKeyPair();
		mPublic = kp.getPublic();
		mPrivate = kp.getPrivate();
	}

	public byte[] encryptRSA(String srcText) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
		
		mCipher.init(Cipher.ENCRYPT_MODE, mPublic);

		byte[] dest = mCipher.doFinal(srcText.getBytes("UTF-8"));
		return dest;
	}
	
	public String decryptRSA(byte[] src) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
		
		mCipher.init(Cipher.DECRYPT_MODE, mPrivate);
		byte[] dest = mCipher.doFinal(src);
		String destText = new String(dest);
		return destText;
	}

}
